package com.fjc.jms;

import com.alibaba.fastjson.JSONObject;
import com.fjc.security.MD5;
import com.fjc.security.Sha256;
import com.fjc.utils.UrlConnectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by fjc on 2019/2/21.
 */
@Component
public class SmsSender {
    @Autowired
    private Sha256 sha256;

    /**
     * 并不通用，需要去重构，但就写写而已
     * @param mobile
     * @param code
     * @return
     * @throws Exception
     */
    public String sendSms(String mobile,String code)throws Exception{

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = simpleDateFormat.format(new Date());
        //1.发送短信
        String url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=1400083020&random=" + code;
        Map<String,Object> map = new HashMap<>();
//        map.put("ext","");
        List<String> params = new ArrayList<>();
        params.add(code);
        params.add("2");
        map.put("params",params);
        String sig = sha256.getSHA256StrJava("appkey=e6efa4a915cccf70dc41932657d1413c&random=" + code + "&time=" + new Date().getTime()/1000 + "&mobile=" + mobile);
        map.put("sig",sig);
        Map<String,String> phone = new HashMap<>();
        phone.put("mobile",mobile);
        phone.put("nationcode","86");
        map.put("tel",phone);
        map.put("time",new Date().getTime()/1000);
        map.put("tpl_id",282409);
        JSONObject json = (JSONObject)JSONObject.toJSON(map);
        String response = UrlConnectUtil.postHttpsJson(url,json);
        System.out.println("腾讯返回：" + response);
        JSONObject returnData = JSONObject.parseObject(response);
        if(returnData.getIntValue("result") == 0){
            System.out.println("短信发送成功");
        }
        return response;
    }
}
